import com.google.appengine.api.datastore.*
import static com.google.appengine.api.datastore.FetchOptions.Builder.*

import wyd.WydCategory

Date now = new Date()
def transcationId = params.transcationKey as int
def transcationKey = ['TranscationE', transcationId] as Key

Entity transcation = datastore.get(transcationKey)
transcation.amount = params.transcationAmount as float
transcation.description = params.transcationDescription
transcation.userId = session.user.id
try {
	def s = "$params.transcationCreatedDateStg $params.transcationCreatedTimeStg"
	def createdTime = new Date().parse('yyyy-MM-dd HH:mm', s)
	use(groovy.time.TimeCategory) {
		int timeZoneHour = session.userTimeZoneHour as int
		int timeZoneMinute = session.userTimeZoneMinute as int
		transcation.createdTime = createdTime - timeZoneHour.hours - timeZoneMinute.minutes
	}
} catch(Throwable t) {
	t.printStackTrace()
	transcation.createdTime = now
}
transcation.updatedTime = now
transcation.save()

//def ttentities = datastore.execute{
//	from TranscationTagE
//	sort asc by name
//	where transcationId == transcation.id and userId == session.user.id
//}
def query = new Query('TranscationTagE')
query.addSort('name', Query.SortDirection.ASCENDING)
query.addFilter('transcationId', Query.FilterOperator.EQUAL, transcation.key.id)
query.addFilter('userId', Query.FilterOperator.EQUAL, session.user.id)
PreparedQuery preparedQuery = datastore.prepare(query)
def ttentities = preparedQuery.asList( withLimit(Integer.MAX_VALUE) )
ttentities.each { transcationTag ->
	transcationTag.delete()
}

if(params.transcationTags != null) {
	params.transcationTags.tokenize('#').each { tag ->
		Entity transcationTag = new Entity('TranscationTagE')
		//transcationTag.id = WydCategory.getNextAutoNumber('transcationTag')
		transcationTag.name = tag.trim()
		transcationTag.transcationId = transcation.key.id
		transcationTag.userId = session.user.id
		transcationTag.createdTime = now
		transcationTag.updatedTime = now
		transcationTag.save()
	}
}

memcache.delete(session.user.id + '-todayTranscations')
memcache.delete(session.user.id + '-weekTranscations')
memcache.delete(session.user.id + '-monthTranscations')

def infoMessage = "Expenses '$transcation.key.id $transcation.amount $transcation.description' updated..."
if(params.json == null) {
	request.infoMessage = infoMessage

	forward 'transcationJQuery.groovy'
}
else {
	println infoMessage
}